package www.openteam.com.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Checkable;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.jakewharton.rxbinding.view.RxView;

import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.functions.Action1;
import www.openteam.com.R;
import www.openteam.com.base.BaseActivity;
import www.openteam.com.bean.Result;
import www.openteam.com.bean.ResultNew;
import www.openteam.com.bean.User;
import www.openteam.com.contract.LoginContract;
import www.openteam.com.mvp.IView;
import www.openteam.com.presenter.LoginPresenter;
import www.openteam.com.tool.SplitXML;
import www.openteam.com.tool.ToastUtil;
import www.openteam.com.view.UserView;

/**
 * Created by kylin on 2016/7/25.
 */
public class LoginActivity extends
        BaseActivity<LoginPresenter>
        implements LoginContract.LoginView {

    @Bind(R.id.input_username)
    EditText input_username;
    @Bind(R.id.input_password)
    TextView input_password;
    @Bind(R.id.loginButton)
    Button lbtn;
    @Bind(R.id.exitButton)
    Button ibtn;
    @Bind(R.id.cb_rpwd)
    Checkable cb_rpwd;

    private final String TAG = LoginActivity.class.getSimpleName();

    int tOptional = 0;
//    //点击登陆按钮
//    @OnClick(R.id.loginButton)
//    public void bLogin() {
//
//    }

    //点击退出按钮
    @OnClick(R.id.exitButton)
    public void bExit() {
        finish();
    }


    @Override
    public String getUserName() {
        return input_username.getText().toString().trim();
    }

    @Override
    public String getPwd() {
        return input_password.getText().toString().trim();
    }

    @Override
    public void loginSuccess(final ResultNew result) {
        mProgressDialog.cancel();
        if (null==result.getData()){
            ToastUtil.showToast(getApplicationContext(),result.getInfo());
            return;
        }
        final SharedPreferences.Editor editor = mySetting.edit();
        //用putString的方法保存数据
        editor.putString("name", getUserName());
        String[] cCodes = null;
        String[] eNames = null;
        String[] moreCom = null;
        String[] prefix = null;
        int num = 0;
        mProgressDialog.dismiss();
        //Log.d(TAG, "loginSuccess: "+result.getData().size());
        List<ResultNew.DataBeanX.DataBean> data = result.getData().getData();
        ResultNew.DataBeanX.DataBean dataBean = data.get(0);
        if (dataBean.getCCode().contains(",")) {
//            "东莞富阳.D,东莞富皓.D-H,黄江裕冠.H-,苏州富扬.S-,中山宝明.Z-,中山宝顺.Z-S",

            cCodes = SplitXML.splitStringString(dataBean.getCCode());
            eNames= SplitXML.splitStringString(dataBean.getEName());
            moreCom= SplitXML.splitStringString(dataBean.getMoreCom());
            prefix= SplitXML.splitStringString(dataBean.getPrefix());
            num = eNames.length;
        }

        final Intent intent = new Intent();
        intent.setClass(LoginActivity.this, HomeActivity.class);
        if (cb_rpwd.isChecked()) {
            editor.putString("pwd", getPwd());
            editor.putBoolean("yon", true);
//
        } else {
            editor.putString("pwd", "");
            editor.putBoolean("yon", false);
        }
//                "mId": 1,
//                "mCode": "Admin",
//                "mName": "系统管理员",
//                "cCode": "01,03,04,02,05,06",
//                "eName": "(东莞富阳.D-),(东莞富皓.D-H),(黄江裕冠.H-),(苏州富扬.S-),(中山宝明.Z-),(中山宝顺.Z-S)",
//                "psCode": null,
//                "psId": null
        editor.putInt("mId", dataBean.getMId());
        editor.putInt("eNum", num);
        editor.putString("mCode", dataBean.getMCode());
        editor.putString("mName", dataBean.getMName());
        //判断是否是销售人员
        if(dataBean.getPsCode()!=null||null!= dataBean.getPsId()){
                    editor.putString("psCode", dataBean.getPsCode()+"");
                    editor.putString("psId", dataBean.getPsId()+"");
                    editor.putBoolean("isSale",true);
        }else{
            editor.putBoolean("isSale",false);
        }
        Log.d(TAG, "loginSuccess: "+ dataBean.getPsCode());
        if (num > 0 && !cCodes.equals(null)) {
            for (int i = 0; i < num; i++) {
                editor.putString("cCode" + i, cCodes[i]);
                editor.putString("eName" + i, eNames[i]);
                editor.putString("moreCom" + i, moreCom[i]);
                editor.putString("prefix" + i, prefix[i]);
                Log.d(TAG, "loginSuccess: "+moreCom[i]+":"+eNames[i]);
            }
        } else {
            editor.putString("rCode", dataBean.getCCode());
//            moreCom= SplitXML.splitStringString(result.getData().get(0).getMoreCom());
            editor.putString("rName", dataBean.getEName());
            editor.putString("rMoreCom", dataBean.getMoreCom() );
            editor.putString("rPrefix", dataBean.getPrefix() );
        }
        editor.commit();
//        startActivity(intent);
//            finish();
        if (num <= 1) {
            startActivity(intent);
            finish();
        } else {
            new AlertDialog.Builder(this)
                    .setTitle("请选择")
                    .setIcon(android.R.drawable.ic_dialog_info)
                    .setSingleChoiceItems(eNames, 0,
                            new DialogInterface.OnClickListener() {

                                public void onClick(DialogInterface dialog, int which) {
                                    tOptional = which;
                                }
                            }
                    )
                    .setNegativeButton("取消", null)
                    .setPositiveButton("选择", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            SharedPreferences getMySetting = getSharedPreferences("mySetting", MODE_PRIVATE);
                            String cCode = getMySetting.getString("cCode" + tOptional, "");
                            String eName = getMySetting.getString("eName" + tOptional, "");
                            String moreCom = getMySetting.getString("moreCom" + tOptional, "");
                            String prefix = getMySetting.getString("prefix" + tOptional, "");
                            editor.putString("rCode", cCode);
                            editor.putString("rName", eName);
                            editor.putString("rMoreCom", moreCom);
                            editor.putString("rPrefix", prefix);
                            Log.d(TAG, "onClick: "+cCode+":"+eName+":"+moreCom+":"+prefix);
                            editor.commit();
                            startActivity(intent);
                            finish();
                        }
                    })
                    .show();
            tOptional = 0;
        }

//        Toast.makeText(this, "登录成功", Toast.LENGTH_LONG).show();
    }




    @Override
    public void loginFail(String failMsg) {
        mProgressDialog.dismiss();
        toast(failMsg);
    }

    public boolean checkNull() {
        boolean isNull = false;
        if (TextUtils.isEmpty(getUserName())) {
            input_username.setError("账号不能为空");
            isNull = true;
        }
        return isNull;
    }


    @Override
    protected LoginPresenter loadPresenter() {

        return new LoginPresenter();
    }

    @Override
    protected void initData() {
//        mySetting = getSharedPreferences("mySetting",
//                Activity.MODE_PRIVATE);
        Boolean yon = mySetting.getBoolean("yon", false);
        if (yon) {
            String name = mySetting.getString("name", "");
            String pwd = mySetting.getString("pwd", "");
            input_username.setText(name);
            input_password.setText(pwd);
            cb_rpwd.setChecked(true);
        }
    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        RxView.clicks(lbtn)
                .throttleFirst(2, TimeUnit.SECONDS)   //两秒钟之内只取一个点击事件，防抖操作
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        createProgressDialog("正在登陆,请稍等...");
                        mPresenter.login(getUserName(), getPwd());
                    }
                });

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void otherViewClick(View view) {

    }

}
